package com.xxq.semester.service.impl.user;

import com.xxq.semester.entity.user.Users;
import com.xxq.semester.mapper.UsersMapper;
import com.xxq.semester.service.user.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 后台用户信息表 服务实现类
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService, UserDetailsService {

    @Override
    public Users getUserByUsername(String username) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }

    @Override
    public Users getUserByEmail(String email) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        return this.getOne(queryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在: " + username);
        }
        
        UserBuilder builder = org.springframework.security.core.userdetails.User.withUsername(username);
        builder.password(user.getPassword());
        
        // 根据用户角色设置权限
        if (user.getRole() != null && "0".equals(user.getRole())) {
            builder.roles("ADMIN");
        } else if (user.getRole() != null && "2".equals(user.getRole())) {
            builder.roles("TEACHER");
        } else {
            builder.roles("USER");
        }
        
        return builder.build();
    }
}
